import { createStore, combineReducers, applyMiddleware } from "redux";
import ReduxThunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";

import axios from "axios";

const LOGOUT = "LOGOUT";
const userInitialState = {};

function userReducer(state = userInitialState, action) {
  switch (action.type) {
    case LOGOUT: {
      return {};
    }
    default:
      return state;
  }
}

// action
export const logout = () => (dispatch) => {
  axios
    .post("/logout")
    .then((res) => {
      if (res.status === 200) {
        dispatch({ type: LOGOUT });
      } else {
        console.log("登出失败", res);
      }
    })
    .catch((err) => console.log("登出失败", err));
};

/**
 * {
 *  user: {},
 *  count: {}
 * }
 */
const allReducers = combineReducers({
  user: userReducer,
});

export default function initializeStore(state) {
  const store = createStore(
    allReducers,
    Object.assign(
      {},
      {
        user: userInitialState,
      },
      state
    ),
    composeWithDevTools(applyMiddleware(ReduxThunk))
  );

  return store;
}
